//
//  HZMapViewController.m
//  projecthz
//
//  Created by tali on 16/8/7.
//  Copyright © 2016年 tali. All rights reserved.
//

#import "HZMapViewController.h"
#import "ClientInfo.h"
#import "PlayerAnnotation.h"
#import "PlayerAnnotationView.h"
#import "UIImageUtil.h"
#import "BuildingAnnotation.h"
#import "BuildingAnnotationView.h"
#import "PlayerCalloutView.h"
#import "BuildingCalloutView.h"

@interface HZMapViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, strong) CLLocationManager      *locationManager;
@property (nonatomic, strong) MKMapView              *mapView;
@property (nonatomic, strong) NSMutableArray         *annotationArray;
@property (nonatomic, strong) PlayerCalloutView      *playCalloutView;
@property (nonatomic, strong) BuildingCalloutView    *buildingCalloutView;

@end

@implementation HZMapViewController

#pragma mark - Init
-(void)viewDidLoad{
    [super viewDidLoad];
    
    [self configUI];
    [self configUserLocation];
}

-(void)configUI{
    [self.view addSubview:self.mapView];
    [self.mapView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    
}

- (void)configUserLocation{
    //启动位置更新
    [self.locationManager startUpdatingLocation];
    
    // 设置焦点
    [self setMapCenterWithCLLocationCoordinate2D:[ClientInfo sharedInstance].userCoordinate];
    
    // 设置user图钉
    PlayerAnnotation *playerAnnotation = [[PlayerAnnotation alloc] initWithCoordinate:[ClientInfo sharedInstance].userCoordinate title:@"" subtitle:@""];
    [self.mapView addAnnotation:playerAnnotation];
}

#pragma mark - MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKAnnotationView * result = nil;
    if ([annotation isKindOfClass:[PlayerAnnotation class]]) {
        PlayerAnnotationView *annoView = (PlayerAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:[PlayerAnnotationView annotationReuseIdentifier]];
        if (annoView==nil) {
            annoView = [[PlayerAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:[PlayerAnnotationView annotationReuseIdentifier]];
            [annoView setCanShowCallout:NO];
            annoView.image = [UIImageUtil imageCompressForWidth:[UIImage imageNamed:@"player"] targetWidth:30];
        }
        return annoView;
    }else if ([annotation isKindOfClass:[BuildingAnnotation class]]){
        BuildingAnnotationView *annoView = (BuildingAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:[PlayerAnnotationView annotationReuseIdentifier]];
        if (annoView==nil) {
            annoView = [[BuildingAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:[BuildingAnnotationView annotationReuseIdentifier]];
            [annoView setCanShowCallout:NO];
            annoView.image = [UIImageUtil imageCompressForWidth:[UIImage imageNamed:@"hospital"] targetWidth:15];
        }
        return annoView;
    }
    return result;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if ([view.annotation isKindOfClass:[PlayerAnnotation class]]){
        [self.playCalloutView setFrame:CGRectMake(view.frame.origin.x + view.frame.size.width/2.f - 36.f, view.frame.origin.y-36.f, 72.f, 36.f)];
        [self.mapView addSubview:self.playCalloutView];
    }else if ([view.annotation isKindOfClass:[BuildingAnnotation class]]){
        [self.buildingCalloutView setFrame:CGRectMake(view.frame.origin.x + view.frame.size.width/2.f - 36.f, view.frame.origin.y-36.f, 72.f, 36.f)];
        [self.mapView addSubview:self.buildingCalloutView];
    }
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    if ([view.annotation isKindOfClass:[PlayerAnnotation class]]){
        if (self.playCalloutView.superview) {// 在视图中
            [self.playCalloutView removeFromSuperview];
        }
    }else if ([view.annotation isKindOfClass:[BuildingAnnotation class]]){
        if (self.buildingCalloutView.superview) {// 在视图中
            [self.buildingCalloutView removeFromSuperview];
        }
    }
}

- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{
    [self markSchoolWithCoordinate:mapView.centerCoordinate];
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    if ([self checkCoordinateEqualBetween:mapView.centerCoordinate and:[ClientInfo sharedInstance].userCoordinate]) {
        return;
    }
    
    [self setMapCenterWithCLLocationCoordinate2D:[ClientInfo sharedInstance].userCoordinate];
}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{
    
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
}

#pragma mark - Private Methods
- (BOOL)checkCoordinateEqualBetween:(CLLocationCoordinate2D)oldCoor and:(CLLocationCoordinate2D)newCoor{
    if ((oldCoor.longitude == newCoor.longitude) && (oldCoor.latitude == newCoor.latitude)) {
        return YES;
    }
    return NO;
}

- (void)setMapCenterWithCLLocationCoordinate2D:(CLLocationCoordinate2D)currentCoor{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.02;//地图缩放大小，数值越小越精细
    span.longitudeDelta = 0.02;
    MKCoordinateRegion region = {currentCoor,span};
    [self.mapView setRegion:region animated:YES];
}

- (void)markSchoolWithCoordinate:(CLLocationCoordinate2D)coordinate{
    MKCoordinateSpan span;
    span.latitudeDelta = 0.05;//地图缩放大小，数值越小越精细
    span.longitudeDelta = 0.05;
    MKCoordinateRegion region = {coordinate,span};
    
    MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
    request.region = region;
    request.naturalLanguageQuery = @"hospital";
    [[[MKLocalSearch alloc] initWithRequest:request] startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){
        if(!error){
            for (MKMapItem *item in [response mapItems]) {
                if (![self checkAnnotationExistWithMapItem:item]) {
                    [self.mapView addAnnotation:[[BuildingAnnotation alloc] initWithMapItem:item]];
                    [self.annotationArray addObject:item];
                    NSLog(@"%@",item.name);
                }
            }
        }else{
            NSLog(@"%@",@"no more place be found.");
        }
    }];
}

-(BOOL)checkAnnotationExistWithMapItem:(MKMapItem *)item{
    BOOL exist = NO;
    if (self.annotationArray.count==0) {
        exist = NO;
    }else{
        for (MKMapItem *mapItem in self.annotationArray) {
            if ([mapItem.name isEqualToString:item.name]) {
                exist = YES;
            }
        }
    }
    return exist;
}

#pragma mark - Getters
-(MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectZero];
        _mapView.delegate = self;
        _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
        _mapView.mapType = MKMapTypeStandard;
        _mapView.showsUserLocation = YES;
        _mapView.zoomEnabled = NO;
        _mapView.scrollEnabled = NO;
    }
    return _mapView;
}

-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        //        [_manager requestAlwaysAuthorization];
        [_locationManager setDelegate:self];
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        if([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_locationManager requestAlwaysAuthorization];
        }
    }
    return _locationManager;
}

-(NSMutableArray *)annotationArray{
    if (!_annotationArray) {
        _annotationArray = [NSMutableArray new];
    }
    return _annotationArray;
}

-(PlayerCalloutView *)playCalloutView{
    if (!_playCalloutView) {
        _playCalloutView = [PlayerCalloutView new];
    }
    return _playCalloutView;
}

-(BuildingCalloutView *)buildingCalloutView{
    if (!_buildingCalloutView) {
        _buildingCalloutView = [BuildingCalloutView new];
    }
    return _buildingCalloutView;
}

@end
